package com.neu.control;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.neu.daoimpl.UsersDaoImpl;
import com.neu.entity.LoginValidateInfo;
import com.neu.entity.TBUsers;
import com.neu.service.UsersService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("哈哈");
		//设定请求和相应的编码集
		//设定响应的编码集
		response.setContentType("text/html; charset=UTF-8");
		//设定请求的编码集
		request.setCharacterEncoding("utf-8");
		//获取页面请求中的数据  用户名和密码
		String name = request.getParameter("username");
		String pass = request.getParameter("pass");
		System.out.println("用户名:"+name+",密码:"+pass);
//		UsersDaoImpl ud = new UsersDaoImpl();
//		try {
//			boolean flag = ud.loginValidate1(new TBUsers(0, name, pass));
//			response.getWriter().write("用户名和密码是:"+flag);
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		
		UsersService udi = new UsersService(new UsersDaoImpl());
		//UsersDaoImpl udi = new UsersDaoImpl();
		try {
			boolean flag =udi.select(name, pass);
			/**
			 * 定义一个java类 LoginValidateInfo 该类用来封装信息提示:
			 *  如果状态值为0提示登录失败;
			 *  如果状态值为1提示登录成功;
			 *  如果flag为true, 则实例化LoginValidateInfo完成状态值和对应的信息赋值
			 *  如果flag为false, 则实例化LoginValidateInfo完成状态值和对应的信息赋值
			 */
			LoginValidateInfo LT;
			Gson g = new Gson();
			String info;
			if(flag) {
				LT=new LoginValidateInfo(1, "登录成功");
				info=g.toJson(LT);
				response.getWriter().write(info);
			}else {
				LT=new LoginValidateInfo(0, "登录失败");
				info=g.toJson(LT);
				response.getWriter().write(info);
			}
			System.out.println("json格式的数据:"+info);
			// 谷歌的GSON  要先实例化
//			Gson gs = new Gson();
//			String s = gs.toJson(flag);
			//将用户名和密码显示在浏览器上,通过response响应对象
//			response.getWriter().write("用户名和密码是:"+flag);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
